#!/usr/bin/python
# -*- coding: UTF-8 -*-

import pandas as pd
import utils

################################################################################
def hrl_head(f):
	f.write('-ifndef(CFG_HRL_).\n')
	f.write('-define(CFG_HRL_, ignore).\n')
	f.write('\n')
	f.write('\n')
	pass

def hrl_end(f):
	f.write('\n')
	f.write('-endif.\n')
	f.close()
	pass

def hrl_record(f, record, df):
	colums = df.columns
	s = '-record(' + record + ', {'
	for c in colums:
		s = s + c + ', '
	s = s[:-2] + '}).\n'
	f.write(s)
	pass


################################################################################
def erl_head(f, record):
	f.write('-module(' + record + ').\n')
	f.write('-export([cfg/1, ids/0]).\n')
	f.write('\n')
	f.write('\n')
	pass

def erl_end(f):
	f.write('cfg(_) -> undefined.\n')
	f.close()
	pass

def erl_ids(f, ids):
	i = 0
	l = ''
	for x in ids:
		if isinstance(x, int):
			s = '%s' % x
		else:
			s = '"%s"' % x
		# 换行
		if i % 10 == 0:
			l += ',\n          ' + s
		else:
			l += ', ' + s
		i += 1
	f.write('ids() -> [' + l[12:] + '].\n')
	f.write('\n')
	pass

def erl_cfg(f, index, row, types, num, record):
	if isinstance(index, int):
		s = 'get_config(%s) -> {%s' % (index, record)
	else:
		s = 'get_config("%s") -> {%s' % (index, record)
	for x in range(num):
		if object == types[x]:
			# utils clear_srv 添加标识 '##'
			if isinstance(row[x], int):
				s += ', %s' % (row[x])
			elif '##' == row[x][:2]:
				s += ', %s' % (row[x][2:])
			else:
				s += ', "%s"' % (row[x])
		else:
			s += ', %s' % (row[x])
	s += '};\n'
	f.write(s)
	pass

def erl(path, name, record, df):
	f = open(path, mode='w', encoding='utf-8')
	erl_head(f, name)
	erl_ids(f, df.index)
	num = df.shape[1]
	for index, row in df.iterrows():
		erl_cfg(f, index, row, df.dtypes, num, record)
	erl_end(f)
	pass


################################################################################
def read_excel(f):
	base = pd.read_excel(f)
	data = utils.clear_srv(base)
	return data


def convert(files):
	print("-- convert erlang")
	path = './../output/erlang/'
	hrl = open(path + 'cfg.hrl', mode='w', encoding='utf-8')
	hrl_head(hrl)
	for file in files:
		name = utils.name(file)
		record = 'cfg_' + name[:-4]
		data = read_excel(file)
		# 空表跳过
		if data.empty:
			continue
		hrl_record(hrl, record, data)
		erl(path + name + '.erl', name, record, data)
		print("erlang: " + path + name + '.erl')
	hrl_end(hrl)


################################################################################
if __name__ == '__main__':
	print('测试输出')
	print('------------------------------------------------')
	convert(['./../excel/example.xlsx'])



